package com.icarsaas.saas.tenant.common.utils;

import com.icarsaas.saas.tenant.config.CurrentTenantIdentifierResolverImpl;
import com.icarsaas.saas.tenant.system.model.User;
import org.apache.shiro.SecurityUtils;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;

/**
 * 当用户提交登陆请求，必须输入租户ID，用来识别要连接哪个数据库。
 * spring security认证机制会自动拦截到租户ID，实现参看:
 * {@link UsernamePasswordAuthenticationFilter} implemented by
 * {@link CustomAuthenticationFilter}. This tenant id is then required by the
 * {@link CurrentTenantIdentifierResolver} implemeted by the
 * {@link CurrentTenantIdentifierResolverImpl}
 * @author Administrator
 *
 */
//@Slf4j
public class TenantContextHolder {
	
    private static final ThreadLocal<String> CONTEXT = new InheritableThreadLocal<>();
    
    public static void setTenantId(String tenant) {
//    	log.info("调用setTenantId***********************设置tenant=" + tenant);
        CONTEXT.set(tenant);
    }

    public static String getTenant() {
    	String tenant = CONTEXT.get();//线程池会发生数据混乱的问题，此时应该优先从登陆用户使用的租户进行获取
    	try {
    		User user = (User) SecurityUtils.getSubject().getPrincipal();
    		if (user != null) {
    			tenant = user.getTenant();
    			TenantContextHolder.setTenantId(tenant);
    		}
    	} catch (Exception e) {// 启动时尚未诸如shiro异常判断无需理会
    	}
//    	log.info("调用getTenant***********************获取tenant=" + tenant);
        return tenant;
    }

    public static void clear() {
        CONTEXT.remove();
    }

}